package org.fxml.utils {
	import org.fxml.IObject;

	import mx.utils.DescribeTypeCache;

	import flash.display.DisplayObjectContainer;
	import flash.utils.ByteArray;
	import flash.utils.Proxy;

	/**
	 * @author jordandoczy
	 * @private
	 */
	public class ObjectUtil {
		
		public static function getValue(chain:*, object:*):*{
			try{
				if(chain == "this") return object;
				if(chain is String){
					chain = chain.replace("[", ".");
					chain = chain.replace("]", "");	
					chain = chain.split(".");
				}
				if(chain[0] == "this") return getValue(chain.slice(1), object);
				
				var property:*; 
				
				if(object is Proxy){
					property = object[chain[0]];
				}
				else if(object is IObject && IObject(object).hasProperty(chain[0])){
					property = IObject(object).getProperty(chain[0]);
				}
				else if(object.hasOwnProperty(chain[0])){
					property = object[chain[0]];
				}
				else if(object is DisplayObjectContainer){
					try{
						property = object.getChildByName(chain[0]);
					}
					catch(e:Error){}
				}
				
				if(chain is Array && chain.length > 1) return getValue(chain.slice(1), property);
				else return property;
			}
			catch(e:Error){
				throw new Error("can not fetch property: " + chain + " on object " + object);
			}
		}
		
		public static function isDynamic(object:*):Boolean {
		    var type:XML = DescribeTypeCache.describeType(object).typeDescription;
		    if(type.isDynamic) return true;
		    return false;
		}
		
		public static function isEqual(value1:*, value2:*):Boolean{
			return value1 === value2;
		}
		
		public static function clone(source:Object):* {
		    var copier:ByteArray = new ByteArray();
		    copier.writeObject(source);
		    copier.position = 0;
		    return(copier.readObject());
		}
		
	}
}